﻿Ext.define('passport.controller.SysUserController',{
    extend: 'Ext.app.Controller',

    stores: ['SysUserStore'],
		/**定义Model*/
    model: ['passport.model.SysUserModel'],

    views: ['sysUser.SysUserEditView', 'sysUser.SysUserListView'],

    refs: [
        {
            ref: 'sysUsersPanel',
            selector: 'panel'
        }
    ],

    init: function() {
        this.control({
        	
            'sysUserEditView button[action=save]': {
                click: this.updateSysUser
            },
			'sysUserListView':{
				itemdblclick: this.editSysUser
			},
			'sysUserListView button[action=create]':{
				click: this.createSysUser
			},
			'sysUserListView button[action=delete]':{
				click: this.deleteSysUser
			},
			'sysUserListView button[action=refresh]':{
				click: this.refreshSysUser
			},
			'permissionTree':{
				itemclick: this.refreshSysUserBySysGroup
			}
        });
    }
    ,

    editSysUser: function(grid, record) {
        var edit = Ext.create('passport.view.sysUser.SysUserEditView').show();
        edit.down('form').loadRecord(record);
    },

    updateSysUser: function(button) {
        var win    = button.up('window'),
            form   = win.down('form'),
            record = form.getRecord(),
            values = form.getValues();

       if (form.getForm().isValid()){
	        record.set(values);
	        var store = this.getStore('SysUserStore');
	        record.save({
	        		success: function() {
	        			store.load();
	        			win.close();
	        		},
	        		failure : function() {
	        		
					Ext.Msg.alert("failed to save SysUser!");
				}
	        	});
	        
      	} else {
      		console.debug('Error occured while saving SysMenu');
      	}
    },
    
    createSysUser: function(grid) {
    	var edit = Ext.create('passport.view.sysUser.SysUserEditView').show();
    	var record = Ext.create('passport.model.SysUserModel');
      edit.down('form').loadRecord(record);
    },
    
    deleteSysUser: function(button) {
    	var gridPanel = button.up("grid");
    	var records = gridPanel.getSelectionModel();
    	var record = records.getSelection()[0];
    	var store = this.getStore('SysUserStore');
    	record.destroy({
	        		  success: function() {
	        			store.load();
	        			console.log("delete object success!");	
	        		},
	        		failure : function() {
	        			console.log("failed to delete the object");
	        		}
	        	});

    	console.log('delete');
    },
    
    refreshSysUser: function() {
    	console.log("refresh");
    	this.getStore('SysUserStore').load();
    },
    
    refreshSysUserBySysGroup: function(node, e){
	    console.log(e.data.id);
	    if(e.data.leaf){
			var store=this.getStore('SysUserStore');
			store.load({params:{filter:'getSysUserBySysGroup', sysGroupId: e.data.id} });
		}	    
    }
});
